﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptObjectWarp : ScriptObject
{
	public enum CallItemStatus
	{
		Create =0,
		Wait = 1,
		End = 2,
	}

	public class DelayCallItem {
		public string funcname;
		public float delay;
		public CallItemStatus status;
		public object[] param;
		//public System.Action<object[]> EndAction;
	}

	protected List<DelayCallItem> m_WaitCallQueue = new List<DelayCallItem>();

	public ScriptObjectWarp(string name) : base(name)   { }

	public ScriptObjectWarp(string name, object[] param) : base(name, param) { }

	public bool ReCtor(string name, object[] param) {
		//判断是否已经初始化
		if (m_Table != null)
			this.Release();
		//初始化当前表结构
		this.LuaClassName = name;
		this.Construct(name, param);
		//重建是否成功
		return this.m_Table != null;
	}

	public void DelayCallFunc(string funcName, float delay, object[] param, System.Action<object[]> action = null)
	{
		DelayCallItem item = new DelayCallItem();
		item.funcname = funcName;
		item.param = param;
		item.delay = delay;
		//if (action != null)
		//	item.EndAction = action;
		item.status = CallItemStatus.Create;
		m_WaitCallQueue.Add(item);
	}
	
	public void DoUpdate(float duration)
	{
		for (int i = 0; i < m_WaitCallQueue.Count; i++)
		{
			var cItem = m_WaitCallQueue[i];
			if (cItem.status == CallItemStatus.Create) {
				cItem.status = CallItemStatus.Wait;
				continue;
			}

			cItem.delay -= duration;
			if(cItem.delay <= 0)
			{
				var succ = this.CallFunc(cItem.funcname, cItem.param);
				if (!succ)
					Debug.LogError($"无法正常调用 {cItem.funcname} 方法");
				cItem.status = CallItemStatus.End;
			}
		}

		for (int i = m_WaitCallQueue.Count - 1; i >= 0; i--)
		{
			var cItem = m_WaitCallQueue[i];
			if(cItem.status == CallItemStatus.End)
			{
				m_WaitCallQueue.Remove(cItem);
			}
		}

	}
}
